import { onMounted, onUnmounted } from 'vue'
import _ from 'lodash'

export default function useScreenAdapt(dWidth: number = 1920, dHeight: number = 1080) {
  // 使用节流提高性能
  const throttleAdjustZoom = _.throttle(() => {
    adjustZoom()
  }, 100)

  // 在组件挂载时需要监听resize事件
  onMounted(() => {
    adjustZoom()
    window.addEventListener('resize', throttleAdjustZoom)
  })

  // 在卸载时需要移出监听事件
  onUnmounted(() => {
    window.removeEventListener('resize', throttleAdjustZoom)
  })

  function adjustZoom() {
    const width = document.documentElement.clientWidth
    const height = document.documentElement.clientHeight
    const scale = Math.min(width / dWidth, height / dHeight)
    
    // 设置根元素font-size，用于rem适配
    document.documentElement.style.fontSize = scale * 16 + 'px'
    
    // 计算水平和垂直方向的居中偏移
    const offsetX = (width - dWidth * scale) / 2
    const offsetY = (height - dHeight * scale) / 2
    
    // 设置缩放和位置
    const appElement = document.getElementById('app')
    if (appElement) {
      appElement.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`
      appElement.style.transformOrigin = '0 0'
      appElement.style.width = `${dWidth}px`
      appElement.style.height = `${dHeight}px`
    }
  }
} 